class Admin::HydropowersController < Admin::ApplicationController
  before_action :set_hydropower, only: [:show, :edit, :update, :destroy, :import_file]

  # GET /admin/hydropowers
  def index
    @hydropowers = Hydropower.all.order(created_at: :desc)
  end

  # GET /admin/hydropowers/1
  def show
  end

  # GET /admin/hydropowers/new
  def new
    @hydropower = Hydropower.new
  end

  # GET /admin/hydropowers/1/edit
  def edit
  end

  # POST /admin/hydropowers
  def create
    @hydropower = Hydropower.new(hydropower_params)

    if @hydropower.save
      redirect_to [:admin, @hydropower], notice: 'Hydropower was successfully created.'
    else
      render :new
    end
  end

  # PATCH/PUT /admin/hydropowers/1
  def update
    if @hydropower.update(hydropower_params)
      redirect_to [:admin, @hydropower], notice: 'Hydropower was successfully updated.'
    else
      render :edit
    end
  end

  # DELETE /admin/hydropowers/1
  def destroy
    @hydropower.destroy
    redirect_to admin_hydropowers_url, notice: 'Hydropower was successfully destroyed.'
  end

  # 导入数据
  def import_file
    begin
      if request.method == 'POST'
        file_excel = params[:excel]
        if file_excel
          file_upload_path = File.expand_path(Rails.root.join("public/uploads/#{file_excel.original_filename}"))
          File.open( file_upload_path, 'wb') { |file| file.write(file_excel.read)}
          result = @hydropower.import_excel(file_upload_path)
          File.delete(file_upload_path)
          redirect_to admin_hydropower_path(@hydropower), notice: '导入成功，数据已经生成'
        else
          flash[:alert] = "没有选择文件"
        end
      end
    rescue => exception
      p '=================='
      p exception.message
      redirect_to admin_hydropower_path(@hydropower), notice: "失败了, #{exception.message}"
    end

  end

  def down_file
    if params[:tag] == 'build_data'
      @hydropower = Hydropower.find(params[:id])
      file = @hydropower.export_excel
      send_file file
    else
      send_file "#{Rails.root}/public/excel/导入数据模版.xlsx"
    end

  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_hydropower
      @hydropower = Hydropower.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def hydropower_params
      params.require(:hydropower).permit(:water_balance, :electric_balance, :total_day)
    end
end
